<template>
  <t-modal
    class="mL"
    ref="modal"
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="loading"
		:destroyOnClose="true"
    @ok="ok"
    @cancel="
      () => {
        $refs.previewModal.resetForm(), $emit('cancel');
      }
    "
  >
    <a-spin :spinning="loading">
        <previewModal
          ref="previewModal"
          :drawingList="drawingList"
          @getJsonData="getJsonData"
          :isView="type === 'view'"
        />
    </a-spin>
    <template slot="footer">
      <a-button key="print" :loading="confirmLoading" @click="reportVisible = true" v-if="reportView.isView && type != 'add'">
				报表预览
			</a-button>
			<a-button key="back" @click="$refs.modal.handleCancel()">
				取消
			</a-button>
			<a-button key="submit" type="primary" :loading="confirmLoading" @click="save()">
				确认
			</a-button>
		</template>
    <reportForm :reportList="reportView" :visible="reportVisible" 
      @update:visible="(v) => {reportVisible = v}" @ok="handleReport"/>
  </t-modal>
</template>

<script>
import previewModal from "@/components/TopVUI/k-form-design/packages/KFormPreview/preview.vue";
import reportForm from "./reportView.vue"
import { baseUrl } from "@/services/baseUrl.js";
import { setTypeList, loadTypeList, getTypeList } from "@/utils/formatter";
import { objToParam,
  randomUUID } from "@/utils/util";
export default {
  name: "TreeList",
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      sameValue: false,
      formUuid: () => this.formUuid
    }
  },
  components: {
    previewModal,
    reportForm,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
		url: {
			type: Object,
			required: true,
		},
		requestMethod: {
			type: String
		},
		tableDataType: {
			type: String
		},
    reportView: {
      type: Object,
      default: () => {}
    },
    isView: {
      type: Boolean
    }
  },
  data() {
    return {
			title: "",
      drawingList: {},
      model: {},
      type: "",
      tableUuid: "",
      loading: false,
      fieldList: [],
      formUuid: false,
      confirmLoading: false,
      reportVisible: false,
    };
  },
  methods: {
    // 获取数据
    loadData(e, type, json, info) {
      console.log(e)
			// 多表的情况下后端返回的数据为数组，要处理下数据格式
			if(info?.length){
				info.forEach(item => {
					this.model[item.tableField] = item.fieldValue
				})
			}else if (info) {
				this.model = info;
			}
      this.type = type;
      this.tableUuid = e;
      this.drawingList = JSON.parse(json);
			this.drawingList.list.forEach(item => {
				if (type === "add") {
          // if(item.type == "uploadFile2"){
          //   this.formUuid = randomUUID();
          // }
					loadTypeList(item);
				} else {
					getTypeList(item, this.model);
          // this.formUuid = this.model.uuid;
				}
        
			});
      // 调用处理函数
      this.handRules(this.drawingList);
      this.$nextTick(() => {
				if (this.$refs.previewModal) {
				  this.$refs.previewModal.jsonData = this.drawingList;
				  this.$refs.previewModal.setData(this.drawingList);
				}
			})
			this.loading = false
    },
    // 编辑的时候处理显隐规则绑定后的数据
    handRules(value) { 
      const rules = value.config.implicitRules;
      const data = value.list;
      rules?.forEach((rule) => {
        const { selectComponentId, selectTableId, selectValueLId, selectValueL, selectOtherComponentId, selectOtherTableId, ifShow, ifRequired } = rule;
        const targetComponent = data.find((item) => item.key === selectOtherComponentId || item.model === selectOtherTableId);
        let shouldHide = false;
        if (selectComponentId.startsWith('checkbox_')) {
          const selectComponent = data.find((item) => item.key === selectComponentId || item.model === selectTableId);
          const arr = selectComponent.options.defaultValue.split(",");
          shouldHide = ifShow === 'show' ? !arr.includes(selectValueL) : arr.includes(selectValueL);
        } else if (selectComponentId.startsWith('input_') || selectComponentId.startsWith('textarea_')) {
          const selectComponent = data.find((item) => item.key === selectComponentId || item.model === selectTableId);
          if (selectComponent) shouldHide = ifShow === 'show' ? selectComponent.options.defaultValue !== selectValueL : selectComponent.options.defaultValue === selectValueL;
        } else {
          const selectComponent = data.find((item) => item.key === selectComponentId || item.model === selectTableId);
          if (selectComponent) shouldHide = ifShow === 'show' ? selectComponent.options.defaultValue !== selectValueL : selectComponent.options.defaultValue === selectValueL;
        }
        // 如果是必填组件，根据隐藏状态去除/增加必填属性
        if(targetComponent){
          if (targetComponent.rules && ifRequired)  targetComponent.rules[0].required = !shouldHide;
          targetComponent.options.hidden = shouldHide;
        }
        if (shouldHide) {
            targetComponent.options.defaultValue = '';
            const nestedTargetComponent = value.list.find(item => item.key === selectOtherComponentId || item.model === selectOtherTableId);
            nestedTargetComponent.options.hidden = true;
        }
      });
    },
    toHump(name) {
      return name.replace(/\_(\w)/g, function(all, letter) {
        return letter.toUpperCase();
      });
    },
    getJsonData(fieldList, json, code) {
      if(this.isView){
        return this.$message.warning('表单预览页面禁止操作数据');
      }
      // this.fieldList = fieldList
      this.drawingList.list.forEach((e, index) => {
        let obj = setTypeList(e, fieldList);
        e = obj.e;
        fieldList = obj.list;
        return;
      });
      this.loading = true;
      // let pramar = fieldList;
			let pramar = {
				list: []
			}
			if(this.tableDataType == 2){
				for(let obj in fieldList){
					this.drawingList.list.map(item => {
						if(item['model'] === obj){
							pramar.list.push({
								tableName: item.tableName,
								tableField: item.model,
								fieldValue: fieldList[obj]
							})
						}
					})
				}
				if(pramar.list.length){
					pramar.list = JSON.stringify(pramar.list)
				}
			}else{
				pramar = fieldList;
			}
			
      pramar.formUuid = this.tableUuid;
			console.log(this.tableUuid)
      if (this.type === "add") {
        this.loading = false;
        pramar.uuid = this.formUuid ? this.formUuid : "";
        let saveUrl = this.splicing(this.url.save, pramar)
        this['$'+this.requestMethod](saveUrl, pramar).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success("新增成功！");
            this.$emit("ok");
            this.$refs.previewModal.resetForm();
          } else {
            this.$message.info(res.message, 1.5);
          }
					setTimeout(() => {
						this.loading = false;
					},200)
					
					// 表单设计全局事件：提交表单后触发
					let fun = eval(code)
					try{
						fun(res)
					}catch(e){
						//TODO handle the exception
					}
					
        });
      } else {
        this.loading = false;
        pramar.uuid = this.model.uuid;
        let updateUrl = this.splicing(this.url.update, pramar)
        this['$'+this.requestMethod](updateUrl, pramar).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success("修改成功！");
            this.$emit("ok");
            this.$refs.previewModal.resetForm();
          } else {
            this.$message.info(res.message, 1.5);
          }
					setTimeout(() => {
						this.loading = false;
					},200)
					
					// 表单设计全局事件：提交表单后触发
					let fun = eval(code)
					try{
						fun(res)
					}catch(e){
						//TODO handle the exception
					}
					
        });
      }
    },
		splicing(url, pramar){
			if(this.requestMethod === 'get' && url.indexOf("?") > -1){
				url = url.replace("?", objToParam(pramar) || "")
			}else if(this.requestMethod === 'get' && url.indexOf("?") === -1){
				url = url + objToParam(pramar)
			}
			return url
		},
    ok() {
			if(this.type === 'view'){
				this.$emit('ok')
				return false
			}
      this.confirmLoading = false
      this.$refs.previewModal.getJsonData();
    },
    save(type = ''){
      this.confirmLoading = true; 
      this.$refs.modal.handleOk()
    },
    handleReport(report) {
      console.log(report)
      this.confirmLoading = true
      setTimeout(() => {
        this.confirmLoading = false
        this.$router.push(
        {
          path: '/report/preview',
          query: {
            url: `${baseUrl}/report/ureport/pdf/show?_u=mysql-${report.name}&uuid=${this.reportView.rowsUuid}&tableName=${this.reportView.database.tableName}`
          }
        })
      }, 1000)
    }
  },
};
</script>

<style lang="scss" scoped>
.ant-form {
  height: auto;
  width: 100%;
}

/* .mL .ant-modal-footer {
		border: none !important;
	} */
</style>
